package com.ipay.wechat.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.response.AlipayUserUserinfoShareResponse;
import com.ipay.utils.Constant;
import com.ipay.wechat.pojo.UserWechatInfo;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ipay.redis.JedisExecutor;
import com.ipay.utils.StringUtil;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.service.UserWechatInfoService;
import com.ipay.wechat.util.ExecuteWeChat;

public class WechatCommonInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private Wechat wechat;
    @Autowired
    private UserWechatInfoService uwiService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        logger.info("wechat afterCompletion");

        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // TODO Auto-generated method stub
        logger.info("wechat afterConcurrentHandlingStarted");
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        logger.info("wechat postHandle");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try {
            String code = request.getParameter("code");
            String auth_code = request.getParameter("auth_code");
            if (StringUtil.isEmpty(code) && StringUtil.isEmpty(auth_code)) {
                return true;
            }
            logger.info("******preHandle-----code======:" + code + "=======auth_code---:" + auth_code);
            String result = "";
            String openid = "";
            String accessToken = "";
            if (StringUtil.isNotEmpty(auth_code)) {
                AlipayUserUserinfoShareResponse userinfoShareResponse = ExecuteWeChat.getAliOauthInfo(auth_code, wechat.getAlipayappid(), wechat.getAlipaykey(), wechat.getAlipaypublickey());
                if (userinfoShareResponse != null && StringUtil.isNotEmpty(userinfoShareResponse.getAlipayUserId())) {
                    openid = userinfoShareResponse.getAlipayUserId();

                    UserWechatInfo userWechatInfo = gainUserAliInfo(userinfoShareResponse);//获得支付宝用户信息
                    if (userWechatInfo != null && StringUtil.isNotEmpty(userWechatInfo.getOpenid())) {
                        UserWechatInfo wechat = uwiService.findOneByOpenidInUserWX(openid);
                        if (wechat != null && StringUtil.isNotEmpty(wechat.getOpenid())) {
                            uwiService.updateWechatUserInfo(userWechatInfo);
                        } else {
                            uwiService.addWechatUserInfo(userWechatInfo);
                        }
                    }
                } else {
                    logger.info("获取支付宝参数错误");
                    return false;
                }
            } else if (StringUtil.isNotEmpty(code)) {
                result = ExecuteWeChat.getOauthInfo(code, wechat.getAppId(), wechat.getSecret()); // 获取用户的openid
                JSONObject jObject = JSONObject.fromObject(result);
                openid = jObject.getString("openid");
                accessToken = jObject.getString("access_token");
            } else {
                logger.info("auth_code与code参数错误");
                return false;
            }
            logger.info("openid==" + openid + "=====" + accessToken);
            /*
			 * WechatUtil wechatUtil=new WechatUtil();
			 * wechatUtil.managerUserInfo(wechat,openid,uwiService);
			 */
            if (StringUtil.isNotEmpty(openid)) {
                logger.info("将openid存入session==" + openid);
                request.getSession().setAttribute("openid", openid);
            }
            if (StringUtil.isNotEmpty(accessToken)) {
                logger.info("将accessToken存入session==" + accessToken);
                request.getSession().setAttribute("accessToken", accessToken);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }

    }


    /**
     * 支付宝数据整理
     * @param userinfoShareResponse
     * @return zhenliu  2017-09-20
     */
    public UserWechatInfo gainUserAliInfo(AlipayUserUserinfoShareResponse userinfoShareResponse) {
        UserWechatInfo userWechatInfo = new UserWechatInfo();
        userWechatInfo.setOpenid(userinfoShareResponse.getAlipayUserId());
        userWechatInfo.setSubscribe(0);
        userWechatInfo.setNickname(userinfoShareResponse.getNickName());
        if (StringUtil.isNotEmpty(userinfoShareResponse.getGender())) {
            if (userinfoShareResponse.getGender().equals("F") || userinfoShareResponse.getGender().equals("f")) {
                userWechatInfo.setSex("2");//性别：F：女性；M：男性    0未知，1男，2女
            } else if (userinfoShareResponse.getGender().equals("M") || userinfoShareResponse.getGender().equals("m")) {
                userWechatInfo.setSex("1");//性别：F：女性；M：男性    0未知，1男，2女
            } else {
                userWechatInfo.setSex("0");//性别：F：女性；M：男性    0未知，1男，2女
            }
        } else {
            userWechatInfo.setSex("0");//性别：F：女性；M：男性    0未知，1男，2女
        }
        userWechatInfo.setProvince(userinfoShareResponse.getProvince());
        userWechatInfo.setCity(userinfoShareResponse.getCity());
        userWechatInfo.setCountry("");
        userWechatInfo.setHeadimgurl(userinfoShareResponse.getAvatar());
        //用户类型（1/2）1代表公司账户2代表个人账户
        // 用户状态（Q/T/B/W）。Q代表快速注册用户  T代表已认证用户  B代表被冻结账户  W代表已注册，未激活的账户
        //是否通过实名认证。T是通过 F是没有实名认证。
        userWechatInfo.setRemark(userinfoShareResponse.getUserTypeValue() + " / " + userinfoShareResponse.getUserStatus() + " / " + userinfoShareResponse.getIsCertified());
        userWechatInfo.setGroupid(0);
        return userWechatInfo;
    }
}
